//
//  DiaryEditReasonTableViewCell.swift
//  MoodDiary
//
//  Created by MoodDiary on 2020/12/8.
//

import UIKit

protocol DiaryEditReasonTableViewCellDelegate: class {
    func diaryEditReason(isOpen: Bool?, selectArray: [String]?)
}

class DiaryEditReasonTableViewCell: UITableViewCell {
    
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var bgView: UIView!
    @IBOutlet weak var btn: UIButton!
    @IBOutlet weak var btn2: UIButton!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var reasonCollectionView: UICollectionView!
    @IBOutlet weak var bgView2: UIView!
    
//    let reasonArray = ["工作", "学习", "音乐", "美食", "亲子", "健身", "娱乐", "购物", "电影", "旅行", "游戏", "晚餐", "礼物", "爱情", "关系", "阅读", "追剧", "运动", "吃瓜", "熬夜", "烹饪", "家庭", "休息", "宠物", "整理", "冒险", "度假", "徒步", "省钱", "露营", "生病", "骑行", "逛街", "动漫", "游泳", "变美", "奶茶", "茶点", "打坐", "养生", "出海", "偶像", "洗澡", "其它"]
    var reasonArray:[[String:Any]] = AppConstant.activeDatasArr
    
    var selectArray: [String]? {
        didSet {
            if selectArray == nil {
                selectArray = []
            }
        }
    }
    var isOpen: Bool? {
        didSet {
            bgView2.isHidden = !(isOpen ?? false)
            bgView.isHidden = (isOpen ?? false)
            btn.setImage(isOpen == true ? UIImage(named: "向上") : UIImage(named: "向下"), for: .normal)
        }
    }
    weak var delegate: DiaryEditReasonTableViewCellDelegate?
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        self.configActiveImagesNames()
        
        bgView.layer.cornerRadius = 12.0
        bgView.layer.borderWidth = 1.0
        bgView.layer.borderColor = UIColor.hexColor(hex: "#E0E0E0").cgColor
        
        bgView2.layer.cornerRadius = 12.0
        bgView2.layer.borderWidth = 1.0
        bgView2.layer.borderColor = UIColor.hexColor(hex: "#E0E0E0").cgColor
        
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UINib(nibName: "DiaryOCCollectionViewCell", bundle: .main), forCellWithReuseIdentifier: "DiaryOCCollectionViewCell")
        
        reasonCollectionView.delegate = self
        reasonCollectionView.dataSource = self
        reasonCollectionView.register(UINib(nibName: "DiaryEditReasonCollectionViewCell", bundle: .main), forCellWithReuseIdentifier: "DiaryEditReasonCollectionViewCell")
        
    }
    
    func configActiveImagesNames(){
        
        if var imgArray = UserDefaults.standard.array(forKey: KUSERActiveImagesArrName ) as? [[String:Any]] {
            
            if let deletedImgArray = UserDefaults.standard.array(forKey: KUSERActiveDeletedImagesArrName) as? [[String:Any]] {
                imgArray.append(contentsOf: deletedImgArray)
            }
            
            reasonArray = imgArray
        }

    }
    
    @IBAction func action() {
        
        superview?.endEditing(true)
        
        delegate?.diaryEditReason(isOpen: !(isOpen ?? false), selectArray: selectArray)
    }
    
}

extension DiaryEditReasonTableViewCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        

        if collectionView == self.collectionView {
            
            let text:String = (selectArray?[indexPath.item])!
            
            let desLabel:UILabel = UILabel.init()
            desLabel.numberOfLines = 0
            let font:UIFont = UIFont.systemFont(ofSize: 12)
            desLabel.text = text

            var size:CGSize = CGSize(width: 120, height: 500);//跟label的宽设置一样
            let dic:Dictionary = [NSAttributedString.Key.font:font]
            size = (desLabel.text?.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic, context: nil).size)!
            return CGSize(width: 52.0 + size.width, height: 30.0)
        }
        
        let marginX = 20.0
        let itemLength = (Double(collectionView.fhh_width) - marginX * 6) / 5 - 5.0

        return CGSize(width: itemLength, height: itemLength + 30.0)
        
        /*根据字宽调整cell宽度，需要改瀑布流，后期需求
        let dic:[String:Any] = (reasonArray[indexPath.item])
        let text:String = dic["text"] as! String
        
        let desLabel:UILabel = UILabel.init()
        desLabel.numberOfLines = 0
        let font:UIFont = UIFont.systemFont(ofSize: 12)
        desLabel.text = text

        var size:CGSize = CGSize(width: 120, height: 500);//跟label的宽设置一样
        let tempfontDic:Dictionary = [NSAttributedString.Key.font:font]
        size = (desLabel.text?.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: tempfontDic, context: nil).size)!
        
        let marginX = 20.0
        let itemLength = (Double(collectionView.width) - marginX * 6) / 5 - 5.0
        
        if size.width > itemLength{
            return CGSize(width: size.width, height: itemLength + 30.0)
        }else{
            return CGSize(width: itemLength, height: itemLength + 30.0)
        }
        */
        

    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        if collectionView == self.collectionView { return .zero }
        return UIEdgeInsets(top: 0, left: 20.0, bottom: 0, right: 20.0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        if collectionView == self.collectionView { return 0 }
        return 20.0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        if collectionView == self.collectionView { return 10.0 }
        return 20.0
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if collectionView == self.collectionView {
            return selectArray?.count ?? 0
        }
        return reasonArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionView == self.collectionView {
            let cell: DiaryOCCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "DiaryOCCollectionViewCell", for: indexPath) as! DiaryOCCollectionViewCell
            cell.label?.text = selectArray?[indexPath.row]
            
            for dic in reasonArray {
                
                if dic["text"] as? String == cell.label?.text{
                    
                    cell.imgV?.image = UIImage(named: dic["imgName"] as? String ?? "" )
                    break
                }
                
            }

            
            if indexPath.row == (selectArray?.count ?? 1) - 1 {
                cell.pointView?.isHidden = true
            } else {
                cell.pointView?.isHidden = false
            }
            return cell
        }
        
        let cell: DiaryEditReasonCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "DiaryEditReasonCollectionViewCell", for: indexPath) as! DiaryEditReasonCollectionViewCell
        
        if let text = reasonArray[indexPath.row]["text"] as? String {
            
            cell.label.text = text
        }
        if let imgName:String = reasonArray[indexPath.row]["imgName"] as? String{
            
            cell.imgV.image = UIImage(named: imgName)
                
        }

        
        if selectArray?.contains(cell.label.text ?? "") == true {
            cell.isSelectCell = true
        } else {
            cell.isSelectCell = false
        }
        
        return cell
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if collectionView == self.collectionView {
            return
        }
        
        let cell: DiaryEditReasonCollectionViewCell = collectionView.cellForItem(at: indexPath) as! DiaryEditReasonCollectionViewCell
        
        
        if let str = reasonArray[indexPath.row]["text"] as? String {
            
            if selectArray?.contains(str) == true {
                selectArray = selectArray?.filter { $0 != str }
                cell.isSelectCell = false
            } else {
                selectArray?.append(str)
                cell.isSelectCell = true
            }
            
        }
        
        delegate?.diaryEditReason(isOpen: nil, selectArray: selectArray)
        
//        collectionView.reloadData()
    }
    
}
